const { Pool } = require("pg");

const config = require("./config");

const pool = new Pool(config);

function poolQuery(sql) {
  return new Promise((resolve, reject) => {
    pool
      .query(sql)
      .then((res) => resolve(res))
      .catch((err) => console.error("Error executing query", err.stack));
  });
}

async function insert(citycode, adcode, name, geojson, center, level, parentId) {
  const [a, b] = adcode.split("");
  const num = parseInt(a + b + "0000");
  await poolQuery(`CREATE TABLE if not exists "t_district_${num}" PARTITION OF "public"."t_district" FOR VALUES FROM (
    '${num}'
    ) TO (
    '${num + 10000}'
    )
    ;`);

  let getformate = (val) => {
    return val ? `'${val}'` : null;
  };

  await poolQuery(`insert into t_district (adcode,citycode,name,the_geom,center,level,parent_id) values('${adcode}',${getformate(citycode)},'${name}',ST_GeomFromGeoJSON('${geojson}'),'${center}','${level}','${parentId}')`);
}

async function insertWithoutGeom(citycode, adcode, name, center, level, parentId) {
  const [a, b] = adcode.split("");
  const num = parseInt(a + b + "0000");
  await poolQuery(`CREATE TABLE if not exists "t_district_${num}" PARTITION OF "public"."t_district" FOR VALUES FROM (
    '${num}'
    ) TO (
    '${num + 10000}'
    )
    ;`);

  let getformate = (val) => {
    return val ? `'${val}'` : null;
  };

  await poolQuery(`insert into t_district (adcode,citycode,name,center,level,parent_id) values('${adcode}',${getformate(citycode)},'${name}','${center}','${level}','${parentId}')`);
}

async function selectByLevel(level) {
  return await poolQuery(`select adcode,level,name,id from t_district where level ='${level}'`);
}

async function updataGeomById(geojson, id) {
  await poolQuery(`UPDATE t_district SET the_geom = ST_GeomFromGeoJSON('${geojson}') WHERE id = ${id} ;`);
}

module.exports = { poolQuery, insert, pool, selectByLevel, insertWithoutGeom, updataGeomById };
